package com.xuchao.rabbit.b8;

import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.DeliverCallback;
import com.xuchao.rabbit.utils.RabbitMqUtils;
import com.xuchao.rabbit.utils.SleepUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author xuchao
 * @Date:2023/6/8 12:38
 * @description
 * @Version 1.0
 */
public class Concumer {
    //普通交换机的名称
    public static final String NORMAL_EXCHANGE = "normal_exchange";
    //死信交换机的名称
    public static final String DEAD_EXCHANGE = "dead_exchange";
    //普通队列的名称
    public static final String NORMAL_QUEUE = "normal_queue";
    //死信队列的名称
    public static final String DEAD_QUEUE = "dead_queue";
    //键
    public static final String NORMAL_ROUTINGKEY = "zhangsan";
    public static final String DEAD_ROUTINGKEY = "lisi";


    public static void main(String[] args) throws Exception {
        Channel channel = RabbitMqUtils.getChannel();
        //声明死信交换机和普通交换机
        channel.exchangeDeclare(NORMAL_EXCHANGE, BuiltinExchangeType.DIRECT);
        channel.exchangeDeclare(DEAD_EXCHANGE,BuiltinExchangeType.DIRECT);

        Map<String,Object> arguments = new HashMap<>();
        //过期时间
        arguments.put("x-message-ttl",10000);
        //正常队列设置过期之后的死信交换机是谁
        arguments.put("x-dead-letter-exchange",DEAD_EXCHANGE);
        //设置死信RoutingKey
        arguments.put("x-dead-letter-routing-key","lisi");
        //队列所能容纳最大长度
        arguments.put("x-max-length",6);
        //声明普通队列
        channel.queueDeclare(NORMAL_QUEUE,false,false,false,arguments);
        //声明死信队列
        channel.queueDeclare(DEAD_QUEUE,false,false,false,null);
        //绑定关系
        channel.queueBind(NORMAL_QUEUE,NORMAL_EXCHANGE,NORMAL_ROUTINGKEY);
        channel.queueBind(DEAD_QUEUE,DEAD_EXCHANGE,DEAD_ROUTINGKEY);

        DeliverCallback deliverCallback = (consumerTag,message)->{
            SleepUtils.sleep(1);
//            通过否定应答并且不重复发送而自动送入死信队列
            System.out.println("转入死信队列:"+new String(message.getBody(),"UTF-8"));
//            channel.basicNack(message.getEnvelope().getDeliveryTag(),false,false);
            channel.basicAck(message.getEnvelope().getDeliveryTag(),false);
        };
        channel.basicConsume(NORMAL_QUEUE,false,deliverCallback,consumerTag -> {});


    }
}
